<template>
  <a-drawer
    :maskClosable="false"
    :title="title"
    :width="800"
    placement="right"
    :closable="false"
    @close="close"
    :visible="visible"
  >

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="合同编号">
          <a-input placeholder="请输入合同编号" v-decorator="['contractid', validatorRules.contractid ]"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="合同名称">
          <a-input placeholder="请输入合同名称" v-decorator="['contractname', validatorRules.contractname ]"/>


        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="说明">
          <a-input placeholder="请输入说明" v-decorator="['remarks', {}]"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="负责人">
          <a-select
            mode="multiple"
            style="width: 100%"
            placeholder="请选择负责人"
            v-model="personList"
            @dropdownVisibleChange="selectUserIds">
          </a-select>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="供应商">
          <a-select
            mode="multiple"
            style="width: 100%"
            placeholder="请选择供应商"
            v-model="supplierList"
            @dropdownVisibleChange="selectUserIds1">
          </a-select>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="采购合同">
          <a-upload
            :action="uploadAction"
            :multiple="true"
            :fileList="fileList"
            @change="handleChange"
            :data="{'isup':1}"
            :headers="headers"
            :beforeUpload="beforeUpload"
          >
            <a-button>
              <a-icon type="upload"/>
              上传
            </a-button>
          </a-upload>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="合同生效日期">
          <a-date-picker v-decorator="[ 'effectivetime', validatorRules.effectivetime ]"/>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="合同失效日期">
          <a-date-picker v-decorator="[ 'endtime', validatorRules.endtime ]"/>
        </a-form-item>

        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="审核人1">
          <a-select
            mode="multiple"
            style="width: 100%"
            placeholder="请选择审核人1"
            v-model="auditor1List"
            @dropdownVisibleChange="selectUserIds2">
          </a-select>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="审核人2">
          <a-select
            mode="multiple"
            style="width: 100%"
            placeholder="请选择审核人2"
            v-model="auditor2List"
            @dropdownVisibleChange="selectUserIds3">
          </a-select>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="审核人3">
          <a-select
            mode="multiple"
            style="width: 100%"
            placeholder="请选择审核人3"
            v-model="auditor3List"
            @dropdownVisibleChange="selectUserIds4">
          </a-select>
        </a-form-item>

      </a-form>
    </a-spin>
    <select-user-list-modal ref="UserListModal" @choseUser="choseUser"></select-user-list-modal>
    <select-user-list-modal ref="UserListModal1" @choseUser="choseUser1"></select-user-list-modal>
    <select-user-list-modal ref="UserListModal2" @choseUser="choseUser2"></select-user-list-modal>
    <select-user-list-modal ref="UserListModal3" @choseUser="choseUser3"></select-user-list-modal>
    <select-user-list-modal ref="UserListModal4" @choseUser="choseUser4"></select-user-list-modal>
    <div class="ant-btn-box">
      <a-button type="primary" @click="handleCancel">取消</a-button>
      <a-button type="primary" @click="handleOk">确定</a-button>
    </div>
  </a-drawer>
</template>

<script>
  import {httpAction} from '@/api/manage'
  import pick from 'lodash.pick'
  import moment from "moment"
  import Vue from 'vue'
  import {getAction} from '@/api/manage'
  import {ACCESS_TOKEN} from "@/store/mutation-types"
  import SelectUserListModal from "./SelectUserListModal";


  export default {
    components: {SelectUserListModal},
    name: "Sys_contractModal",
    data() {
      return {
        title: "操作",
        visible: false,
        model: {},
        labelCol: {
          xs: {span: 24},
          sm: {span: 5},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16},
        },

        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules: {
          contractid: {rules: [{required: true, message: '请输入合同编号!'}]},
          contractname: {rules: [{required: true, message: '请输入合同名称!'}]},
          person: {rules: [{required: true, message: '请输入负责人!'}]},
          supplier: {rules: [{required: true, message: '请输入供应商!'}]},
          effectivetime: {rules: [{required: true, message: '请输入合同生效日期!'}]},
          endtime: {rules: [{required: true, message: '请输入合同失效日期!'}]},
        },
        uploadLoading: false,
        headers: {},
        url: {
          queryByrealname: "/sys/user/queryByrealname",
          fileUpload: window._CONFIG['domianURL'] + "/sys/common/upload",
          add: "/contract/sys_contract/add",
          edit: "/contract/sys_contract/edit",
        },
        fileList: [],
        personList: [],
        person: [],
        supplierList: [],
        supplier: [],
        auditor1List: [],
        auditor1: [],
        auditor2List: [],
        auditor2: [],
        auditor3List: [],
        auditor3: [],
        disabled: false,
        msgContent: "",
      }
    },

    created() {
      const token = Vue.ls.get(ACCESS_TOKEN);
      this.headers = {"X-Access-Token": token}
    },
    computed: {
      uploadAction: function () {
        return this.url.fileUpload;
      }
    },
    methods: {
      add() {
        this.edit({});
      },
      edit(record) {
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;

        this.person = record.person;
        this.supplier = record.supplier;
        this.auditor1 = record.auditor1;
        this.auditor2 = record.auditor2;
        this.auditor3 = record.auditor3;
        getAction(this.url.queryByrealname, {name: this.person}).then((res) => {
          if (res.success) {
            for (var i = 0; i < res.result.length; i++) {
              this.personList.push(res.result[i].realname);
            }
            this.$refs.UserListModal.edit(res.result, this.person);
          }
        })
        getAction(this.url.queryByrealname, {name: this.supplier}).then((res) => {
          if (res.success) {
            for (var i = 0; i < res.result.length; i++) {
              this.supplierList.push(res.result[i].realname);
            }
            this.$refs.UserListModal.edit(res.result, this.supplier);
          }
        })
        getAction(this.url.queryByrealname, {name: this.auditor1}).then((res) => {
          if (res.success) {
            for (var i = 0; i < res.result.length; i++) {
              this.auditor1List.push(res.result[i].realname);
            }
            this.$refs.UserListModal.edit(res.result, this.auditor1);
          }
        })
        getAction(this.url.queryByrealname, {name: this.auditor2}).then((res) => {
          if (res.success) {
            for (var i = 0; i < res.result.length; i++) {
              this.auditor2List.push(res.result[i].realname);
            }
            this.$refs.UserListModal.edit(res.result, this.auditor2);
          }
        })
        getAction(this.url.queryByrealname, {name: this.auditor3}).then((res) => {
          if (res.success) {
            for (var i = 0; i < res.result.length; i++) {
              this.auditor3List.push(res.result[i].realname);
            }
            this.$refs.UserListModal.edit(res.result, this.auditor3);
          }
        })

        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'id', 'contractid', 'contractname', 'remarks', 'person', 'supplier', 'avatarfile', 'auditor1', 'auditor2', 'auditor3'))
          //时间格式化
          this.form.setFieldsValue({effectivetime: this.model.effectivetime ? moment(this.model.effectivetime) : null})
          this.form.setFieldsValue({endtime: this.model.endtime ? moment(this.model.endtime) : null})
        });

      },

      close() {
        this.$emit('close');
        this.person = [];
        this.visible = false;
      },
      handleOk() {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if (!this.model.id) {
              httpurl += this.url.add;
              method = 'post';
            } else {
              httpurl += this.url.edit;
              method = 'put';
            }
            let formData = Object.assign(this.model, values);
            //时间格式化
            formData.person = this.person;
            formData.supplier = this.supplier;
            formData.auditor1 = this.auditor1;
            formData.auditor2 = this.auditor2;
            formData.auditor3 = this.auditor3;
            formData.effectivetime = formData.effectivetime ? formData.effectivetime.format() : null;
            formData.endtime = formData.endtime ? formData.endtime.format() : null;

            console.log(formData)
            httpAction(httpurl, formData, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.$emit('ok');
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }
        })
      },
      handleCancel() {
        this.close()
        this.resetUser();
      },

      handleChange(info) {
        let fileList = [...info.fileList];
        fileList = fileList.slice(-2);
        fileList = fileList.map((file) => {
          if (file.response) {
            file.url = file.response.url;
          }
          return file;
        });
        this.fileList = fileList

        if (info.file.status === 'uploading') {
          this.uploadLoading = true
          return
        }
        if (info.file.status === 'done') {
          var response = info.file.response;
          this.uploadLoading = false;
          console.log(response);
          if (response.success) {
            this.model.avatarfile = response.message;
          } else {
            this.$message.warning(response.message);
          }
        }
      },
      beforeUpload: function (file) {
        var fileType = file.type;
        if (fileType.indexOf('pdf') < 0) {
          this.$message.warning('请上传PDF文件');
          return false;
        }
        //TODO 验证文件大小
      },
      resetUser() {
        this.personList = [];
        this.person = [];
        this.supplierList = [];
        this.supplier = [];
        this.auditor1List = [];
        this.auditor1 = [];
        this.auditor2List = [];
        this.auditor2 = [];
        this.auditor3List = [];
        this.auditor3 = [];
        this.disabled = false;
        this.$refs.UserListModal.edit(null, null);
      },
      selectUserIds() {
        this.$refs.UserListModal.add(this.personList, this.person);
      },
      selectUserIds1() {
        this.$refs.UserListModal1.add(this.supplierList, this.supplier);
      },
      selectUserIds2() {
        this.$refs.UserListModal2.add(this.auditor1List, this.auditor1);
      },
      selectUserIds3() {
        this.$refs.UserListModal3.add(this.auditor2List, this.auditor2);
      },
      selectUserIds4() {
        this.$refs.UserListModal4.add(this.auditor3List, this.auditor3);
      },

      // 负责人子modal回调
      choseUser: function (userList) {
        this.personList = [];
        this.person = [];
        for (var i = 0; i < userList.length; i++) {
          this.personList.push(userList[i].realname);
          this.person += userList[i].realname + ","
        }
      },
      // 供应商子modal回调
      choseUser1: function (userList) {
        this.supplierList = [];
        this.supplier = [];
        for (var i = 0; i < userList.length; i++) {
          this.supplierList.push(userList[i].realname);
          this.supplier += userList[i].realname + ","
        }
      },
      // 审核人子modal回调
      choseUser2: function (userList) {
        this.auditor1List = [];
        this.auditor1 = [];
        for (var i = 0; i < userList.length; i++) {
          this.auditor1List.push(userList[i].realname);
          this.auditor1 += userList[i].realname + ","
        }
      },
      // 审核人子modal回调
      choseUser3: function (userList) {
        this.auditor2List = [];
        this.auditor2 = [];
        for (var i = 0; i < userList.length; i++) {
          this.auditor2List.push(userList[i].realname);
          this.auditor2 += userList[i].realname + ","
        }
      },
      // 审核人子modal回调
      choseUser4: function (userList) {
        this.auditor3List = [];
        this.auditor3 = [];
        for (var i = 0; i < userList.length; i++) {
          this.auditor3List.push(userList[i].realname);
          this.auditor3 += userList[i].realname + ","
        }
      },
    }
  }
</script>

<style lang="less" scoped>
  /** Button按钮间距 */
  .ant-btn-box{
    width:65%;
    button:first-child{
      background:#f18200;
      border:1px solid #f18200;
      &:hover{
        background:#f1a700;
        border:#f1a700;
      }
    }
  }
  .ant-btn {
    margin-left: 30px;
    margin-bottom: 30px;
    float: right;
    width:100px;
  }
</style>